package org.liubility.robot.config;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author JDragon
 * @Date 2021.02.18 下午 11:27
 * @Email 1061917196@qq.com
 * @Des:
 */
@Slf4j
@Configuration
public class ThreadPoolPoolConfig {

    /**
     * 读取配置文件的信息
     */
    @Autowired
    private TaskThreadPoolProperty config;

    @Bean("asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        log.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //线程池核心线程数
        taskExecutor.setCorePoolSize(config.getCorePoolSize());
        //线程池最大线程数
        taskExecutor.setMaxPoolSize(config.getMaxPoolSize());
        //缓冲队列
        taskExecutor.setQueueCapacity(config.getQueueCapacity());
        //线程名称前缀
        taskExecutor.setThreadNamePrefix(config.getNamePrefix());
        //线程空闲后的最大存活时间
        taskExecutor.setKeepAliveSeconds(60);
        //rejection-policy：当pool已经达到max size的时候，如何处理新任务
        //CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        //对拒绝task的处理策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        taskExecutor.initialize();
        return taskExecutor;
    }
}

